import os
import sys
from colorama import init, Fore, Back, Style

# 初始化colorama
init(autoreset=True)


class GomokuGame:
    def __init__(self, size=15):
        self.size = size  # 棋盘大小
        self.board = [['.' for _ in range(size)] for _ in range(size)]  # 初始化棋盘
        self.current_player = 'X'  # 当前玩家
        self.game_over = False
        self.winner = None
        self.player_colors = {
            'X': Fore.RED + Style.BRIGHT,
            'O': Fore.GREEN + Style.BRIGHT
        }

    def clear_screen(self):
        """清空屏幕"""
        os.system('cls' if os.name == 'nt' else 'clear')

    def print_header(self):
        """打印游戏标题"""
        title = f"{Back.BLUE}{Fore.WHITE}{Style.BRIGHT} 五指棋游戏 {Style.RESET_ALL}"
        print(f"\n{' ' * 20}{title}")
        print(
            f"{' ' * 15}{Fore.YELLOW}玩家 {self.player_colors['X']}X{Fore.YELLOW} 和 {self.player_colors['O']}O{Fore.YELLOW} 轮流下棋")
        print(f"{' ' * 10}{Fore.CYAN}输入行号和列号 (0-{self.size - 1}) 来放置棋子{Style.RESET_ALL}\n")

    def print_board(self):
        """打印彩色棋盘"""
        # 打印列号
        col_header = "    " + " ".join([f"{i:2}" for i in range(self.size)])
        print(f"{Back.LIGHTBLACK_EX}{Fore.WHITE}{col_header}{Style.RESET_ALL}")

        for i, row in enumerate(self.board):
            # 打印行号
            row_header = f"{Back.LIGHTBLACK_EX}{Fore.WHITE}{i:2} |{Style.RESET_ALL}"

            # 打印棋盘内容
            row_content = []
            for j, cell in enumerate(row):
                # 设置棋盘背景色（棋盘格效果）
                bg_color = Back.LIGHTWHITE_EX if (i + j) % 2 == 0 else Back.LIGHTYELLOW_EX

                if cell == 'X':
                    display = f"{bg_color}{self.player_colors['X']} X{Style.RESET_ALL}"
                elif cell == 'O':
                    display = f"{bg_color}{self.player_colors['O']} O{Style.RESET_ALL}"
                else:
                    # 空位置显示为点
                    display = f"{bg_color}{Fore.LIGHTBLACK_EX} .{Style.RESET_ALL}"

                row_content.append(display)

            print(row_header + " ".join(row_content))

    def is_valid_move(self, row, col):
        """检查落子位置是否有效"""
        if row < 0 or row >= self.size or col < 0 or col >= self.size:
            return False
        return self.board[row][col] == '.'

    def make_move(self, row, col):
        """玩家落子"""
        if self.game_over:
            return False

        if not self.is_valid_move(row, col):
            return False

        self.board[row][col] = self.current_player
        if self.check_win(row, col):
            self.game_over = True
            self.winner = self.current_player
            return True

        # 切换玩家
        self.current_player = 'O' if self.current_player == 'X' else 'X'
        return True

    def check_win(self, row, col):
        """检查是否获胜"""
        player = self.board[row][col]

        # 检查方向：水平、垂直、两个对角线
        directions = [(0, 1), (1, 0), (1, 1), (1, -1)]

        for dr, dc in directions:
            count = 1  # 当前位置已经有一个棋子

            # 正向检查
            r, c = row + dr, col + dc
            while 0 <= r < self.size and 0 <= c < self.size and self.board[r][c] == player:
                count += 1
                r += dr
                c += dc

            # 反向检查
            r, c = row - dr, col - dc
            while 0 <= r < self.size and 0 <= c < self.size and self.board[r][c] == player:
                count += 1
                r -= dr
                c -= dc

            # 如果有5个连续的棋子，获胜
            if count >= 5:
                return True

        return False

    def play(self):
        """开始游戏"""
        self.clear_screen()
        self.print_header()

        while not self.game_over:
            self.print_board()

            # 显示当前玩家
            player_color = self.player_colors[self.current_player]
            print(f"\n{player_color}玩家 {self.current_player} 的回合{Style.RESET_ALL}")

            try:
                row = int(input("请输入行号: "))
                col = int(input("请输入列号: "))

                if not self.make_move(row, col):
                    print(f"{Fore.RED}无效的位置！请重新选择。{Style.RESET_ALL}")
                    input("按Enter继续...")
                    self.clear_screen()
                    self.print_header()
                    continue

                self.clear_screen()
                self.print_header()

            except ValueError:
                print(f"{Fore.RED}请输入有效的数字！{Style.RESET_ALL}")
                input("按Enter继续...")
                self.clear_screen()
                self.print_header()
                continue

        # 游戏结束
        self.clear_screen()
        self.print_header()
        self.print_board()

        # 显示获胜信息
        winner_color = self.player_colors[self.winner]
        win_message = f"{Back.GREEN}{Fore.WHITE}{Style.BRIGHT} 玩家 {winner_color}{self.winner}{Fore.WHITE} 获胜！ {Style.RESET_ALL}"
        print(f"\n{' ' * 20}{win_message}")
        print(f"\n{' ' * 15}{Fore.CYAN}游戏结束！感谢游玩！{Style.RESET_ALL}")
        print("\n" + "=" * 60)


# 开始游戏
if __name__ == "__main__":
    print(f"{Back.BLUE}{Fore.WHITE}{Style.BRIGHT} 五指棋游戏加载中... {Style.RESET_ALL}")
    game = GomokuGame()
    game.play()